<?php
$db = new Database();
$this->view->current_user = Auth::getAuth('current_user');
$auth = Auth::getAuth('current_user');
$userID = $auth['userID'];
$password = $auth['Password'];
if(isset($_POST['action'])){
    if($_POST['action']=="DeleteUser"){
	$ID_listed = $_POST['ID_listed'];
	$splid_ID = explode(",",$ID_listed);
	$count_ID = count($splid_ID);
	for($a=0;$a<$count_ID;$a++){
	    $getID = $db->query("SELECT * FROM users WHERE userID='$splid_ID[$a]'","array");
	    foreach($getID as $data){
		$ID = $data['userID'];
		$conditions = array("userID"=>$ID);
		$db->delete("users",$conditions);
		// Audit Trail
		$insert = array("userID"=>$auth['userID'],
			       "actionID"=>11,
			       "affectedTable"=>"users",
			       "affectedRecord"=>$ID,
			       "datetime"=>date("Y-m-d  H:i:s")
			       );
		 $db->insert("audit_trail",$insert);
	    }
	}
    // Add new User
    }elseif($_POST['action']=="editUser"){
	$ID = $_POST['ID'];
	$userFname = $_POST["userFname"];
        $userUname = $_POST["userUname"];
        $userLname = $_POST["userLname"];
        $userUtype = $_POST["userUtype"];
        $userActive = $_POST["userActive"];
        $userDept = $_POST["userDept"];
	$uUserLocation = $_POST['uUserLocation'];
	$fields = array("Firstname"=>$userFname,
			"Lastname"=>$userLname,
			"UserType"=>$userUtype,
			"Username"=>$userUname,
			"UserDept"=>$userDept,
			"UserLocation"=>$uUserLocation,
			"is_active"=>$userActive
			);
	$conditions = array("UserID"=>$ID);
	$db->update("users",$fields,$conditions);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>10,
			   "affectedTable"=>"users",
			   "affectedRecord"=>$ID,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
    // Delete User from the database of tblusers
    }elseif($_POST['action']=="addNewUser"){
	$userFname = $_POST["userFname"];
        $userUname = $_POST["userUname"];
        $userLname = $_POST["userLname"];
        $userUtype = $_POST["userUtype"];
        $userActive = $_POST["userActive"];
        $userDept = $_POST["userDept"];
	$userPassword = md5($_POST["userPassword"]);
	$fieldsAdd = array("Firstname"=>$userFname,
			"Lastname"=>$userLname,
			"UserType"=>$userUtype,
			"Username"=>$userUname,
			"is_active"=>$userActive,
			"Password"=>$userPassword
			);
	$newUser = $db->insert("users",$fieldsAdd);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>9,
			   "affectedTable"=>"users",
			   "affectedRecord"=>$newUser,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
    // Delete User from the database of tblusers
    }elseif($_POST['action']=="saveTag"){
	$taggedWidth = $_POST['taggedWidth'];
	$taggedHeight = $_POST['taggedHeight'];
	$taggedTop = $_POST['taggedTop'];
	    $taggedTop = str_replace("px", "", $taggedTop);
	
	$taggedLeft = $_POST['taggedLeft'];
	    $taggedLeft = str_replace("px", "", $taggedLeft);
	$imageID = $_POST['imageID'];
	
	$portnumber = $_POST['portnumber'];
	$cabinet = $_POST['cabinetName'];
	$statusBlink = $_POST['statusBlink'];
	$workstationType = $_POST['workstationType'];
	$description = $_POST['description'];
	$IPAddress = $_POST['IPAddress'];
	$mac = $_POST['mac'];
	$vLan = $_POST['vLan'];
	$directoryName = $_POST['directoryName'];
	$localNumber = $_POST['localNumber'];
	$StationType = $_POST['StationType'];
	$ttIPAddress = $_POST['ttIPAddress'];
	$EAPBX = $_POST['EAPBX'];
	$COS = $_POST['COS'];
	/* Extra Added Fiels */
	$etf1 = $_POST['etf1'];
	$etf2 = $_POST['etf2'];
	$insert = array("width"=>$taggedWidth,
			"height"=>$taggedHeight,
			"top"=>$taggedTop,
			"getleft"=>$taggedLeft,
			"fileID"=>$imageID,
			"portNumber"=>$portnumber,
			"cabinet"=>$cabinet,
			"userID"=>$userID,
			"workstation"=>$workstationType,
			"description"=>$description,
			"ipAddress"=>$IPAddress,
			"mac"=>$mac,
			"directoryName"=>$directoryName,
			"stationType"=>$StationType,
			"eaPBX"=>$EAPBX,
			"classService"=>$COS,
			"vLan"=>$vLan,
			"localNumber"=>$localNumber,
			"statusBlink"=>$statusBlink,
			"ttipAddress"=>$ttIPAddress,
			"imageID"=>$imageID,
			"dateCreated"=>date("Y-m-d  H:i:s"),
			"etf1"=>$etf1,
			"etf2"=>$etf2
			);
			
	$lastTagged = $db->insert("tag",$insert);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>7,
			   "affectedTable"=>"tag",
			   "affectedRecord"=>$lastTagged,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
	echo $lastTagged; // Return last inserted id
    // Delete Selected Tag from the database
    }elseif($_POST['action']=="deleteTag"){
	$tagID = $_POST['tagID']; // Tag Information ID
	$imageID = $_POST['imageID']; // Image ID
	
	// Process to delete the selected tag
	$conditions = array("id"=>$tagID);
	$db->delete("tag",$conditions);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>6,
			   "affectedTable"=>"tag",
			   //"affectedRecord"=>$insert,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
	echo "Tag Deleted.";
    // Allow user to update the tag
    }elseif($_POST['action']=="updateTag"){
	$taggedWidth = $_POST['taggedWidth'];
	$taggedHeight = $_POST['taggedHeight'];
	$taggedTop = $_POST['taggedTop'];
	    $taggedTop = str_replace("px", "", $taggedTop);
	
	$taggedLeft = $_POST['taggedLeft'];
	    $taggedLeft = str_replace("px", "", $taggedLeft);
	$imageID = $_POST['imageID'];
	
	$tagID = $_POST['tagID'];
	
	$portnumber = $_POST['portnumber'];
	$cabinet = $_POST['cabinetName'];
	$statusBlink = $_POST['statusBlink'];
	$workstationType = $_POST['workstationType'];
	$description = $_POST['description'];
	$IPAddress = $_POST['IPAddress'];
	$mac = $_POST['mac'];
	$vLan = $_POST['vLan'];
	$directoryName = $_POST['directoryName'];
	$localNumber = $_POST['localNumber'];
	$StationType = $_POST['StationType'];
	$ttIPAddress = $_POST['ttIPAddress'];
	$EAPBX = $_POST['EAPBX'];
	$COS = $_POST['COS'];
	/* Extra added Fields */
	$etf1 = $_POST['etf1'];
	$etf2 = $_POST['etf2'];
	$set = array("width"=>$taggedWidth,
			"height"=>$taggedHeight,
			"top"=>$taggedTop,
			"getleft"=>$taggedLeft,
			"fileID"=>$imageID,
			"portNumber"=>$portnumber,
			"cabinet"=>$cabinet,
			"userID"=>$userID,
			"workstation"=>$workstationType,
			"description"=>$description,
			"ipAddress"=>$IPAddress,
			"mac"=>$mac,
			"directoryName"=>$directoryName,
			"stationType"=>$StationType,
			"eaPBX"=>$EAPBX,
			"classService"=>$COS,
			"vLan"=>$vLan,
			"localNumber"=>$localNumber,
			"statusBlink"=>$statusBlink,
			"ttipAddress"=>$ttIPAddress,
			"imageID"=>$imageID,
			"dateCreated"=>date("Y-m-d  H:i:s"),
			"etf1"=>$etf1,
			"etf2"=>$etf2
			);
	$conditions = array("id"=>$tagID);
	$db->update("tag",$set,$conditions);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>8,
			   "affectedTable"=>"tag",
			   "affectedRecord"=>$tagID,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
    //Save Created Cabinet
    }elseif($_POST['action']=="saveCabinet"){
	$positionCounter = $_POST['positionCounter'];
	$cabinetName = $_POST['cabinetName'];
	$cab = $_POST['update'];
	$editedCab = $_POST['cabinet'];
	$removesaveCabinetDB = str_replace("saveCabinetDB ", "", $editedCab);
	$remvoespacerProperties = str_replace("spacerProperties", "", $removesaveCabinetDB);
	$replaceimageProperties = str_replace("imageProperties", "viewImage", $remvoespacerProperties);
	$saveCreatedCabinet = stripslashes($replaceimageProperties);
	
	    // Location where user want to create a folder for their new cabinet
	    $cabinetLocation = "images/cabinet/".$cabinetName;
	
	    // Create a text file where the created cabinet to be saved as textfiles
	    $editedCabinet = $cabinetLocation."/".$cabinetName.".txt";
	    $fh = fopen($editedCabinet, 'w') or die("can't open file");
		fwrite($fh, $saveCreatedCabinet);
	    fclose($fh);
	
	$cab = stripslashes($cab); 
	    $originalCabinet = $cabinetLocation."/".$cabinetName."_original.txt";
	    $fh1 = fopen($originalCabinet, 'w') or die("can't open file");
		fwrite($fh1, $cab);
	    fclose($fh1);
	
	//Save to the cabinet
	$setCab = array("cabinetLocation"=>$cabinetLocation,
			   "editedCabinet"=>$editedCabinet,
			   "originalCabinet"=>$originalCabinet);
	$con = array("cabinetName"=>$cabinetName);
	$db->update("cabinet",$setCab,$con);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>12,
			   "affectedTable"=>"cabinet",
			   //"affectedRecord"=>$insert,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
	echo "Yes";
    }elseif($_POST['action']=="existingCabinet"){
	$cabinetList = $db->query("SELECT * FROM cabinet WHERE is_active='1'","array");
	$count = $db->query("SELECT * FROM cabinet WHERE is_active='1'","numrows");
	if($count==0){
	    echo "No Cabinet.";
	}else{
	    echo "<select class='selection' name='fileCabinet'>";
	    foreach($cabinetList as $cabinet){
		echo "<option>".$cabinet['cabinetName']."</option>";
	    }
	    echo "</select>";
	}
    }elseif($_POST['action']=="createCabinet"){
	echo '<input type="text" name="fileCabinet" id="fileCabinet" class="textfield_one" />';
    // Delete uploaded image
    }elseif($_POST['action']=="deleteThisImage"){
	$imageID = $_POST['fileID'];
	$imageList = $db->query("SELECT * FROM file WHERE fileID='$imageID'","row");
	unlink($imageList['fileLocation']);
	unlink($imageList['thumbnail']);
	//delete($table,$conditions=array())
	    $conditions = array("fileID"=>$imageID);
	    $db->delete("file",$conditions);
	    $db->delete("tag",$conditions);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>5,
			   "affectedTable"=>"file & tag",
			   //"affectedRecord"=>$insert,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
	echo "File was successfully deleted";
    }elseif($_POST['action']=="showCabinetInRight"){
	$cabinetID = $_POST['cabinetID'];
	$getCreatedCabinet = $db->query("SELECT * FROM cabinet WHERE id='$cabinetID'","row");
	// Open Textfile
	if($getCreatedCabinet['editedCabinet']==""){
	    echo "Empty";
	}else{
	    $myFile = $getCreatedCabinet['editedCabinet'];
	    $fh = fopen($myFile, 'r');
	    $theData = fread($fh, filesize($myFile));
	    fclose($fh);
	    echo $theData;
	}
    }elseif($_POST['action']=="editCabinetCreated"){
	$cabinetID = $_POST['cabinetID'];
	$getCreatedCabinet = $db->query("SELECT * FROM cabinet WHERE id='$cabinetID'","row");
	// Open Textfile
	if($getCreatedCabinet['originalCabinet']==""){
	    echo "Empty";
	}else{
	    $myFileoriginalCabinet = $getCreatedCabinet['originalCabinet'];
	    $fhoriginalCabinet = fopen($myFileoriginalCabinet, 'r');
	    $originalCabinet = fread($fhoriginalCabinet, filesize($myFileoriginalCabinet));
	    fclose($fhoriginalCabinet);
	    echo $originalCabinet;
	}
/*------------------------------------------------------------------------------------------------------------*/
    // Edit user information
    }elseif($_POST['action']=="editInformation"){
	$firstname = $_POST['firtname'];
	$lastname = $_POST['lastname'];
	$division = $_POST['division'];
	$location = $_POST['location'];
	$userID = $_POST['userID'];
	if($firstname==""||$lastname==""||$location==""){
	    echo "Please dont leave those blank field's.";
	}else{
	    $set = array("Firstname"=>$firstname,
			"Lastname"=>$lastname,
			"UserDept"=>$division,
			"UserLocation"=>$location);
	    $condition = array("userID"=>$userID);
	    $db->update("users",$set,$condition);
	    $login = $db->query("SELECT *
                                    FROM users
                                    WHERE userID={$db->escape($userID)} ","row");
        Auth::setAuth('current_user',$login);
	    echo "Info was successfully  updated.";
	    // Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>13,
			   "affectedTable"=>"users",
			   "affectedRecord"=>$userID,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
	}
    // Edit Username and change it to a new one
    }elseif($_POST['action']=="newUsername"){
	$new_username = $_POST['newUsername'];
	$conditions = array("userID"=>$userID);
	$fields = array("Username"=>$new_username);
	$db->update("users",$fields,$conditions);
	$login = $db->query("SELECT *
                                    FROM users
                                    WHERE userID={$db->escape($userID)} ","row");
        Auth::setAuth('current_user',$login);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>13,
			   "affectedTable"=>"users",
			   "affectedRecord"=>$userID,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
    // Edit Password and change it to a new one
    }elseif($_POST['action']=="newPassword"){
	$new_password = md5($_POST['newPassword']);
	$oldPassword = md5($_POST['oldPassword']);
	if($password!=$oldPassword){
	    echo "no";
	}else{
	    $conditions = array("userID"=>$userID);
	    $fields = array("Password"=>$new_password);
	    $db->update("users",$fields,$conditions);
	    $login = $db->query("SELECT *
                                    FROM users
                                    WHERE userID={$db->escape($userID)} ","row");
        Auth::setAuth('current_user',$login);
	// Audit Trail
	    $insert = array("userID"=>$auth['userID'],
			   "actionID"=>13,
			   "affectedTable"=>"users",
			   "affectedRecord"=>$userID,
			   "datetime"=>date("Y-m-d  H:i:s")
			   );
	     $db->insert("audit_trail",$insert);
	}
    // Delete Folder from the database
    }elseif($_POST['action']=="DeleteCabinet"){
	$cabinetID = $_POST['cabinetID'];
	
	$getID = $db->query("SELECT * FROM cabinet WHERE id='$cabinetID'","array");
	foreach($getID as $cabinet){
	    $dbcabID = $cabinet['id'];
	    $dbcabLoc = $cabinet['cabinetLocation'];
	    $dbcabName = $cabinet['cabinetName'];
	}
	    $parent_dir = opendir($dbcabLoc); // Complete Path
	    $directory = $dbcabLoc;
	    
	    $c = 0; 
	    while($contents = readdir($parent_dir)&& $c<3)
	    {
		$c++;
		if($contents != "." && $contents != "..")
		{
		    
		}
	    }
	    // Validation if folder directory is empty or not
	    if($c>2)
	    {
		echo "This folder have a file of the server.";
	    }else{
		// Deleting Folder from the database and from the directory
		//$conditions = array("FolderID"=>$dbfoldeID);
		//$db->delete("tblfolders",$conditions);
		//rmdir($directory);
		//echo "Folder was successfully deleted.";
		echo "You dont have any created server on this folder.";
	    }
	
	    
    }
}
?>